import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Descriptions, Spin } from 'antd';
import { formatDateTime } from '@/utils/datetime';
import { getStatusTag } from '@/utils/status';
import { submissionService } from '@/services/submissionService';
import CodeMirror from '@uiw/react-codemirror';
import { cpp } from '@codemirror/lang-cpp';
import { java } from '@codemirror/lang-java';
import { python } from '@codemirror/lang-python';
import { formatMemoryMB } from '@/utils/mappings';
import styles from './Detail.module.css';

const getLanguageExtension = (language: string) => {
  switch (language) {
    case 'C':
    case 'C++':
      return cpp();
    case 'Java':
      return java();
    case 'Python3':
      return python();
    default:
      return cpp();
  }
};

const SubmissionDetail: React.FC = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState(true);
  const [submission, setSubmission] = useState<any>(null);

  useEffect(() => {
    fetchSubmissionDetail();
  }, [id]);

  const fetchSubmissionDetail = async () => {
    try {
      setLoading(true);
      const response = await submissionService.getSubmissionDetail(id!);
      setSubmission(response.data.data);
    } catch (error) {
      console.error('Failed to fetch submission detail:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <Spin size="large" className={styles.loading} />;
  }

  if (!submission) {
    return <div>提交记录不存在</div>;
  }

  return (
    <div className={styles.container}>
      <Card title="提交详情" className={styles.card}>
        <Descriptions bordered column={2}>
          <Descriptions.Item label="提交时间">
            {formatDateTime(submission.create_time)}
          </Descriptions.Item>
          <Descriptions.Item label="题目">
            {submission.problem_title}
          </Descriptions.Item>
          <Descriptions.Item label="用户">
            {submission.username}
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            {getStatusTag(submission.result)}
          </Descriptions.Item>
          <Descriptions.Item label="语言">
            {submission.language}
          </Descriptions.Item>
          <Descriptions.Item label="耗时">
            {submission.statistic_info.time_cost} ms
          </Descriptions.Item>
          <Descriptions.Item label="内存">
            {formatMemoryMB(submission.statistic_info.memory_cost)}
          </Descriptions.Item>
        </Descriptions>

        <div className={styles.codeSection}>
          <h3>代码</h3>
          <CodeMirror
            value={submission.code}
            height="400px"
            theme="light"
            editable={false}
            extensions={[getLanguageExtension(submission.language)]}
          />
        </div>
      </Card>
    </div>
  );
};

export default SubmissionDetail; 